<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/11/18
 * Time: 13:48
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\api\controller\v1;

use app\api\controller\Base;
use app\api\controller\Payment;
use app\common\business\Grabbing;
use app\common\business\GrabSheet;
use app\common\business\Run;
use app\common\business\Sex;
use app\common\business\Site;
use app\common\lib\Show;
use app\common\lib\Status;
use think\Exception;

class Order extends Base
{
    public function getOrderList()
    {
        //查询所有支付成功且抢单状态为未抢单的
        $limit = $this->request->param('limit', 10, 'intval');
        $page = $this->request->param('page', 1, 'intval');
        $lat = $this->request->param('lat', '', 'trim');
        $lng = $this->request->param('lng', '', 'trim');
        $map = [];
        //获取设置
        $run = (new Run())->getRunByDistanceById();
        $distace = $run['distance'] ?? 5;
        $kilometers = Show::getKilometers($lat, $lng, $distace);
        $map = [
            ["address_lat", "between", $kilometers['min']],
            ['address_lng', "between", $kilometers['max']]
        ];
        try {
            $lists = (new \app\common\business\PlaceOrder())->getOrderList($limit, $page, $map);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "ok", $lists['data'], $lists['total']);
    }

    public function getOrderById()
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id || $id == 0) {
            return Show::json_show(Status::mini_error, "状态错误");
        }
        try {
            $order = (new \app\common\business\PlaceOrder())->getBaseById($id, '*,is_lou as set_lou,weight as set_weight,description as set_desc,is_gui as set_gui');
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        //获取地址
        if ($order) {
            $order = $order->toArray();
            if ($order['payStatus'] != 1) {
                return Show::json_show(Status::mini_error, "订单支付状态错误");
            }
//            $site = (new Site())->getBaseById((int)$order['start_address']);
//            $order['site'] = "";

            try {
                $xain = (new Grabbing())->getBaseById((int)$order['xian'], '*');
            } catch (\Exception $e) {
                throw new Exception("内部错误");
            }
            $order['xian'] = $xain['title'] ?? "";
            if ($order['state'] == 1) {
                $order['mobile'] = substr_replace($order['mobile'], '****', 3, 4);
//                $order['express_order'] = substr_replace($order['express_order'], '****', 3, strlen($order['express_order']) - 3);
//                $order['end_address'] = substr_replace($order['end_address'], '****', 3, strlen($order['end_address']) - 3);
//                $order['site'] = substr_replace($order['site'], '****', 3, strlen($order['site']) - 3);
                $order['idCard'] = substr_replace($order['idCard'], '****', 3, strlen($order['idCard']) - 3);
                //$order['sex'] = substr_replace($order['sex'],'****',1,2);
                $order['idCard_f'] = "";
                $order['idCard_z'] = "";
                $order['idPath'] = "";
                $order['wx'] = "******";
                $order['order_id'] = substr_replace($order['order_id'], '******', 3, strlen($order['order_id']) - 5);
                $order['express_order'] = "*****";
                $order['qcode'] = "*****";
            } else {
                $order['idCard_f'] = (string)url("/" . $order['idCard_f'], [], false, true);
                $order['idCard_z'] = (string)url("/" . $order['idCard_z'], [], false, true);
                $order['idPath'] = (string)url("/" . $order['idPath'], [], false, true);
            }
            $order['site'] = $order['start_address'] . " " . $order['address_qu_info'];
            return Show::json_show(Status::mini_normal, "ok", $order);
        } else {
            return Show::json_show(Status::mini_error, "数据查询失败");
        }
    }

    public function getGrabById()
    {
        $id = $this->request->param('id', 0, 'intval');
        $latitude = $this->request->param('latitude', '', 'trim');
        $longitude = $this->request->param('longitude', '', 'trim');

        $openid = $this->request->param('openid', '', 'trim');
        if (!$id || $id == 0) {
            return Show::json_show(Status::mini_error, "系统内部错误！请稍后重试");
        }
        try {
            $order = (new \app\common\business\PlaceOrder())->getBaseById($id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "订单不存在");
        }
        if (!$order) {
            return Show::json_show(Status::mini_error, "订单不存在");
        }
        $distance = Show::getDistance($order['address_lng'], $order['address_lat'], $longitude, $latitude, 2);
        //查询系统设置的骑手限制距离
        try {
            $run = (new Run())->getRunByDistanceById();
        } catch (\Exception $e) {
            Show::json_show(Status::mini_error, "查询失败");
        }
        $dis = $run['distance'] ?? 5;
        if ($dis < $distance) {
            return Show::json_show(Status::mini_error, "您的距离太远");
        }
        //根据openid查询骑手是否认证成功
        try {
            $auth = (new \app\common\business\Auth())->getAuthByOpenid($openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "系统内部错误");
        }
        if (!$auth) {
            return Show::json_show(Status::mini_error, "您还没有认证");
        }
        if ($auth['state'] != 1) {
            return Show::json_show(Status::mini_error, "您的认证还未通过");
        }
        //判断抢单限制
        if ($order['xian'] == 2) { //只能男生
            if ($auth['sex'] != 1) {
                return Show::json_show(Status::mini_error, "只能男生接单哟");
            }
        } else if ($order['xian'] == 3) { //只能女生
            if ($auth['sex'] != 0) {
                return Show::json_show(Status::mini_error, "只能女生接单");
            }
        }
        try {
            $res = (new \app\common\business\PlaceOrder())->getOrderByGrabId($id, $openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }

        return Show::json_show(Status::mini_normal, "抢单成功");
    }

    public function getUserOrder()
    {
        $type = $this->request->param('type', 99, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        $page = $this->request->param('page', 1, 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        try {
            $order = (new \app\common\business\PlaceOrder())->getUserOrder($type, $limit, $page, $openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, 'ok', $order);
    }

    /**
     * 获取骑手订单
     * @return \think\response\Json
     */
    public function getGrabOrder()
    {
        $type = $this->request->param('type', 99, 'intval');
        $limit = $this->request->param('limit', 10, 'intval');
        $page = $this->request->param('page', 1, 'intval');
        $openid = $this->request->param('openid', '', 'trim');
        try {
            $order = (new GrabSheet())->getGrabOrder($type, $limit, $page, $openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, 'ok', $order);
    }

    /**
     * @return \think\response\Json
     */
    public function setGrabByData()
    {
        $id = $this->request->param('id', 0, 'intval');
        $type = $this->request->param('type', 0, 'intval');
        if ($id == 0 || $type == 0) {
            return Show::json_show(Status::mini_error, "内部错误");
        }
        try {
            (new GrabSheet())->setGrabByData($id, $type);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        return Show::json_show(Status::mini_normal, "操作成功");

    }

    public function getLastOrder()
    {
        $openid = $this->request->param('openid', '', 'trim');
        if (empty($openid)) {
            return Show::json_show(Status::mini_error, "内部发生错误");
        }
        try {
            $order = (new \app\common\business\PlaceOrder())->getLastOrder($openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        if (!$order) {
            $order = [];
        } else {
            $order = $order->toArray();
        }
        return Show::json_show(Status::mini_normal, "ok", $order);
    }

    public function setUserByStateSuccess()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id == 0) {
            return Show::json_show(Status::mini_error, "错误");
        }
        $openid = $this->request->param('openid','','trim');
        $placeOrder = new \app\common\business\PlaceOrder();
        try {
            $result = $placeOrder->setStateByOrder($id,$openid);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, $e->getMessage());
        }
        if ($result) {
            return Show::json_show(Status::mini_normal, "操作成功");
        } else {
            return Show::json_show(Status::mini_error, "操作失败");
        }
    }
}